package com.hengpeng.itfinoss.controller.partner;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.constants.TransCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.PartnerTransType;
import com.hengpeng.itfinbase.message.partner.QueryAcctsRequestMsg;
import com.hengpeng.itfinbase.message.partner.QueryAcctsResponseMsg;
import com.hengpeng.itfinbase.message.partner.TransferRequest;
import com.hengpeng.itfinbase.persist.Partner;
import com.hengpeng.itfinbase.persist.Partner.PartnerStatus;
import com.hengpeng.itfinbase.persist.Partner.PartnerType;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.service.ServiceFactory;

@Controller
@RequestMapping("/partner")
public class PartnerController extends BaseController
{

	@Autowired
	private ServiceFactory serviceFactory;

	@RequestMapping(value = "/list")
	public String partnerList(ModelMap map, HttpServletRequest request, String id_text, String name_text)
	{
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		List<Partner> list = new ArrayList<Partner>();
		map.put("id_text", id_text);
		map.put("name_text", name_text);
		Long id = null;
		Pattern pattern = Pattern.compile("[0-9]*");
		if (id_text != null && !"".equals(id_text) && pattern.matcher(id_text).matches())
		{
			id = Long.parseLong(id_text);
		}
		else
		{
			id = null;
		}
		QueryResult<Partner> result = serviceFactory.getPartnerService().findPartnerWithPage(id, name_text,
				page.currentPage, page.pageSize, null);
		page.setEntityCount((int) result.getTotalCount());
		list = result.getResults();
		map.put("list", list);
		map.put("page", page);
		return "stm/partner/list";
	}

	@RequestMapping(value = "/detail/{id}")
	public String detail(ModelMap map, HttpServletRequest request, @PathVariable Long id)
	{
		Partner partner = serviceFactory.getPersistService().get(Partner.class, String.valueOf(id));
		if (partner == null)
		{
			return returnError(map, "无法找到该商户！");
		}

		QueryAcctsRequestMsg requestMsg = new QueryAcctsRequestMsg();
		requestMsg.setPartnerTransType(PartnerTransType.QueryAccts);
		requestMsg.setMerCustId(partner.getMerchantId());
		requestMsg.setTransType(TransCodeConstants.PartnerTransCode.REQUEST);
		QueryAcctsResponseMsg queryAccts = (QueryAcctsResponseMsg) serviceFactory.getRemoteService().remoteTrans(
				requestMsg);
		map.put("queryAccts", queryAccts);
		map.put("partner", partner);
		return "stm/partner/detail";
	}

	@RequestMapping(value = "/modify")
	public String modifypartner(ModelMap map, HttpServletRequest request, Long id, String name, String remark,
			PartnerStatus status, String extConfigString, PartnerType type)
	{
		Partner partner = serviceFactory.getPersistService().get(Partner.class, id);
		if (partner == null)
		{
			return returnError(map, "无法找到该商户！");
		}
		partner.setName(name);
		partner.setRemark(remark);
		partner.setStatus(status);
		partner.setPartnerType(type);
		Map<String, String> config = new HashMap<String, String>();
		if (extConfigString != null && extConfigString.length() > 2)
		{
			if (extConfigString.indexOf("{") == 0 && extConfigString.indexOf("}") == extConfigString.length() - 1)
			{
				try
				{
					extConfigString = extConfigString.substring(1, extConfigString.length() - 1);
					config = getConfigByStr(extConfigString, ",");
				}
				catch (Exception e)
				{
					return returnError(map, "商户配置信息数据没有通过验证，请重试！");
				}
			}
			else
			{
				return returnError(map, "商户配置信息数据没有通过验证，请重试！");
			}
		}
		partner.setExtConfigs(config);
		try
		{
			partner = serviceFactory.getPersistService().update(partner);
			ServiceResult<Partner> result = new ServiceResult<Partner>(partner);
			result.setMessage("商户更新成功");
			return returnSuccess(map, result, "/partner/list");
		}
		catch (Exception e)
		{
			return returnError(map, "短信商户更新失败！");
		}
	}

	@RequestMapping(value = "/add")
	public String addpartner(ModelMap map, HttpServletRequest request)
	{
		Partner partner = new Partner();
		Map<String, String> config = new HashMap<String, String>();
		partner.setExtConfigs(config);
		map.put("partner", partner);
		return "stm/partner/detail";
	}

	@RequestMapping(value = "/save")
	public String save(ModelMap map, HttpServletRequest request, Long id, String name, String remark,
			PartnerStatus status, String extConfigString, PartnerType type)
	{
		Partner partner = serviceFactory.getPersistService().get(Partner.class, id);
		if (partner != null)
		{
			return returnError(map, "短信商户编号重复！");
		}
		partner = new Partner();
		partner.setName(name);
		partner.setRemark(remark);
		partner.setStatus(status);
		partner.setCreateTime(new Date());
		partner.setPartnerType(type);
		Map<String, String> config = new HashMap<String, String>();
		if (extConfigString != null && extConfigString.length() > 2)
		{
			if (extConfigString.indexOf("{") == 0 && extConfigString.indexOf("}") == extConfigString.length() - 1)
			{
				try
				{
					extConfigString = extConfigString.substring(1, extConfigString.length() - 1);
					config = getConfigByStr(extConfigString, ",");
				}
				catch (Exception e)
				{
					return returnError(map, "商户配置信息数据没有通过验证，请重试！");
				}
			}
			else
			{
				return returnError(map, "商户配置信息数据没有通过验证，请重试！");
			}
		}
		partner.setExtConfigs(config);
		try
		{
			partner = serviceFactory.getPersistService().save(partner);
			ServiceResult<Partner> result = new ServiceResult<Partner>(partner);
			result.setMessage("短信商户添加成功");
			return returnSuccess(map, result, "/partner/List");
		}
		catch (Exception e)
		{
			return returnError(map, "商户添加失败！");
		}
	}

	private Map<String, String> getConfigByStr(String text, String split)
	{
		Map<String, String> result = new HashMap<String, String>();
		if (text != null)
		{
			text = text.trim();
			String[] entrys = text.split("\\" + split);
			for (String entry : entrys)
			{
				String[] values = entry.split("\\=");
				if (values.length == 2)
				{
					result.put(values[0].trim(), values[1].trim());
					System.out.println(values[0] + "=" + values[1]);
				}
			}
		}
		return result;
	}
}
